package com.sys.framework.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sys.common.core.domain.model.LoginUser;
import com.sys.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author LGY
 * Create by 2024/5/29 15:16
 */
@Slf4j
@Component
public class SysMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert值自动插入填充");
        LoginUser currentUser = this.getCurrentUser();
        this.strictInsertFill(metaObject, "createBy", String.class, currentUser != null ? currentUser.getId() : null);
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update值自动插入填充");
        LoginUser currentUser = this.getCurrentUser();
        this.strictUpdateFill(metaObject, "updateBy", String.class, currentUser != null ? currentUser.getId() : null);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }

    private LoginUser getCurrentUser() {
        LoginUser currentUser = null;
        try {
            currentUser = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            log.error("获取用户信息异常");
        }
        return currentUser;
    }
}
